/*
 * Hidden Equity LLC
 * Author: Maksym Fedyay, Kyiv, mcsimf@gmail.com
 * Date: 29.02.2012
 */

package com.hiddenequity.acts;

import java.util.ArrayList;
import java.util.Map;

import com.hiddenequity.adgroup_ad_service.AdGroupAdResponseParser;
import com.hiddenequity.adgroup_ad_service.AdGroupAdService;
import com.hiddenequity.report_definition_service.PredicateOperator;
import com.hiddenequity.report_definition_service.ReportDefinitionResponseParser;
import com.hiddenequity.report_definition_service.ReportDefinitionService;
import com.hiddenequity.report_definition_service.ReportDialog;
import com.hiddenequity.report_definition_service.ReportField;
import com.hiddenequity.report_definition_service.ReportType;
import com.hiddenequity.utils.AppPreferences;
import com.hiddenequity.utils.AuthService;
import com.hiddenequity.utils.Communication;
import com.hiddenequity.utils.DateProcessor;
import com.hiddenequity.utils.UrlBuncher;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class Act_AdList extends Act_Super {
	
	private static ArrayList<Map<String, String>> adList = new ArrayList<Map<String, String>>();
	
	private String campaignName;
	private String adGroupName;
	private String adGroupId;
	
	private int dateRangeItem;
	private int statusItem;

	private Spinner spinnerDateRange;
	private Spinner spinnerStatus;
	

	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_ad_list);
		
		new AuthService(this, getApplication());
		
		Intent intent = getIntent();
		adGroupId = intent.getStringExtra("adGroupId");
        campaignName = intent.getStringExtra("campaignName");
        adGroupName = intent.getStringExtra("adGroupName");
        
        title.setText(getString(R.string.title_ad_list));
        sub_title.setText(campaignName + " / " + adGroupName);
        
        //Populate date range list
        spinnerDateRange = (Spinner) findViewById(R.id.spin_CampaignDateRange);
        dateRangeItem = AppPreferences.LoadPreferenceInt("dateRange", 0, getApplication());
        inflateSpinner(spinnerDateRange, R.array.arr_dateRanges, dateRangeItem);
         
        spinnerDateRange.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                try {
                	if(pos != dateRangeItem){
                		AppPreferences.SavePreferenceInt("dateRange", pos, getApplication());
                		dateRangeItem = pos;
                		runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
                	}
				} catch (Exception e) {
					e.printStackTrace();
				}
            	
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
            
        });

        //Populate status list
        spinnerStatus = (Spinner) findViewById(R.id.spin_CampaignStatus);
        statusItem = AppPreferences.LoadPreferenceInt("status", 0, getApplication());
        inflateSpinner(spinnerStatus, R.array.arr_status, statusItem);
        
        spinnerStatus.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                try {
                	if(pos != statusItem){
                		AppPreferences.SavePreferenceInt("status", pos, getApplication());
                		statusItem = pos;
                		runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
                	}
				} catch (Exception e) {
					e.printStackTrace();
				}
            	
            }
            public void onNothingSelected(AdapterView<?> parent) {
            }
            
        }); 

        
		//Filter toggler
		filterToggler(AppPreferences.LoadPreferenceInt("filterToggle", 0, getApplication()));
		final Button btn_toggleFilter = (Button) findViewById(R.id.btn_toggleFilter);
		btn_toggleFilter.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				LinearLayout filter = (LinearLayout) findViewById(R.id.ll_filter);
				filterToggler(filter.getVisibility());
			}
		});
        
        
        //List view 
        final ListView lv = (ListView) findViewById(R.id.list_Ad);
        registerForContextMenu(lv);
        lv.setAdapter(textAdListAdapter);
        
        runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_loading), false);
	}

	
    /*
     * Handles requested activity result
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
		if(resultCode == Act_Super.RESPONSE_FINISH_REQUIRED){
	    	finishActivityWithResult(RESPONSE_FINISH_REQUIRED);
		} else if(resultCode == Act_Super.RESPONSE_GOTO_MAIN_ACTIVITY){
			finishActivityWithResult(RESPONSE_GOTO_MAIN_ACTIVITY);
		} else if(requestCode == REQUEST_REFRESH_REQUIRED && resultCode == RESPONSE_REFRESH_REQUIRED){
	    	runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
		}
   	}//onActivityResult  
	
	
	
    /*
     * Inflate Context menu when long press occurred (non-Javadoc)
     */
    private String selectedAdId;
    private String selectedTextAdHeadline;
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
  
    	switch (v.getId()) {
        	
			case R.id.list_Ad: 
			    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
			    ListView list = (ListView) v;
			    
				Map<String, String> itemMap = (Map<String, String>) list.getItemAtPosition(info.position);

			    selectedAdId = itemMap.get("id");
			    selectedTextAdHeadline = itemMap.get("headline");
				String status = itemMap.get("status");
				
			    menu.add(0, 1, 0, R.string.ad_general);
			    menu.add(0, 2, 0, R.string.performance_report);
			    
			    if(!status.equals("ENABLED"))
			    	menu.add(0, 3, 0, R.string.status_active);
			    
			    if(!status.equals("PAUSED"))
			    	menu.add(0, 4, 0, R.string.status_pause);
			    
			    if(!status.equals("DELETED"))
			    	menu.add(0, 5, 0, R.string.status_delete);
				
				break;
    	}
      	menu.setHeaderTitle(getString(R.string.tit_context_ad));
    }//onCreateContextMenu

    
    
    /*
     * Context menu selection handler  (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	Intent intent;
    	
    	switch (item.getItemId()) {
        
    		case 1: 
    			intent = new Intent(this.getApplicationContext(), Act_AdOperation.class);
    			intent.putExtra("adId", selectedAdId);
    			intent.putExtra("adGroupId", adGroupId);
    			intent.putExtra("campaignName", campaignName);
    			intent.putExtra("adGroupName", adGroupName);
    			
    			startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);            	
                break;
 
    		case 2: 
           		String[] fields = new String[] {
        			ReportField.HEADLINE,
        			ReportField.CLICKS,
        			ReportField.COST,
        			ReportField.IMPRESSION,
        			ReportField.STATUS,
        			ReportField.AVERAGE_POSITION,
        			ReportField.CONVERSIONS
           		};

            	String[] predicateValue = new String[]{
            			selectedAdId
        		};
        			
        		String[] predicates = new String[]{
        				ReportDefinitionService.setPredicator(ReportField.ID, 
        						PredicateOperator.EQUALS, predicateValue)
        		};

        		String reportDefinition = ReportDefinitionService.defineReport(
            			ReportType.AD_PERFORMANCE_REPORT, fields, dateRangeItem, predicates);
            	String report = Communication.requestAdHogRequest(UrlBuncher.URL_ADHOC_REPORT, reportDefinition);
            	ReportDefinitionResponseParser parser = new ReportDefinitionResponseParser(report);
        		ArrayList<Map<String, String>> columns = parser.getReportColumns();
            	ArrayList<Map<String, String>> rows = parser.getReportRows(columns);
        		ReportDialog.showReport(Act_AdList.this, rows, columns, 0, R.string.msg_title_ad_report).show();
                break;
                
    		case 3: 
            	statusSetTo = STATUS_ACTIVE;
            	runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
                break;
                
            case 4: 
            	statusSetTo = STATUS_PAUSED;
            	runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
                break;
                
            case 5: 
            	statusSetTo = STATUS_DELETED;
            	
    			new AlertDialog.Builder(this)
						.setTitle(R.string.msg_title_conf_delete)		
						.setMessage(getString(R.string.msg_conf_textad_delete) + " " + quote + selectedTextAdHeadline + "..." + quote + "?")
		    			.setPositiveButton(R.string.btn_Yes, deletionConfirmationListener)
			    		.setNegativeButton(R.string.btn_No, deletionConfirmationListener)
			    		.setCancelable(false)
			    		.create()
			    		.show();
            	
                break;
        }
        return true;
    }//onContextItemSelected

 
    
	/*
	 * Dialog onClick Listener
	 */
	private DialogInterface.OnClickListener deletionConfirmationListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {

			switch (which){
		        case DialogInterface.BUTTON_POSITIVE:
		        	runOperationAsync(OPERATION_SET_STATUS, getString(R.string.progress_applying), false);
		            break;
	
		        case DialogInterface.BUTTON_NEGATIVE:
		        	//Do nothing on cancel
		            break;
	        }
	        
		}
	};//DialogClickListener
    
    
    
	/*
	 * Change ad status
	 */
	private void setAdStatus(){
		
		String response = Communication.postSOAP(
				AdGroupAdService.URL_ADGROUP_AD_SERVICE,
				AdGroupAdService.setAdStatus(adGroupId, selectedAdId, statusSetTo));

		AdGroupAdResponseParser parser = new AdGroupAdResponseParser(response);
		
		responseErrorString = parser.checkForErrors();		
	}//setAdGroupStatus
    
	
	
	/*
     * Base adapter for ad list
     */
	private BaseAdapter textAdListAdapter = new BaseAdapter() {

		public int getCount() {
			int size = Act_AdList.adList.size();
			return size;
		}

		public Object getItem(int position) {
			return Act_AdList.adList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;

			if (row == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				row = mInflater.inflate(R.layout.list_row_ad, null);
			}

			TextView adId = (TextView) row.findViewById(R.id.ad_Id);
			TextView adStatus = (TextView) row.findViewById(R.id.ad_Status);
			TextView ad_AppruvalStatus = (TextView) row.findViewById(R.id.ad_AppruvalStatus);
			TextView ad_headline = (TextView) row.findViewById(R.id.ad_headline);
			TextView ad_description1 = (TextView) row.findViewById(R.id.ad_description1);
			TextView ad_description2 = (TextView) row.findViewById(R.id.ad_description2);
			TextView ad_displayUrl = (TextView) row.findViewById(R.id.ad_displayUrl);
			TextView ad_url = (TextView) row.findViewById(R.id.ad_url);
			
			TextView ad_clicks_value = (TextView) row.findViewById(R.id.ad_clicks_value);
			TextView ad_cost_value = (TextView) row.findViewById(R.id.ad_cost_value);
			TextView ad_ctr_value = (TextView) row.findViewById(R.id.ad_ctr_value);
			TextView ad_avgcpc_value = (TextView) row.findViewById(R.id.ad_avgcpc_value);

			ImageView img_ad_status  = (ImageView) row.findViewById(R.id.img_ad_status);
			
			adId.setText(Act_AdList.adList.get(position).get("id"));
			ad_AppruvalStatus.setText(Act_AdList.adList.get(position).get("approvalStatus"));

			ad_url.setText(Act_AdList.adList.get(position).get("url"));
			
			
			ad_headline.setText(Act_AdList.adList.get(position).get("headline"));
			ad_description1.setText(Act_AdList.adList.get(position).get("description1"));
			ad_description2.setText(Act_AdList.adList.get(position).get("description2"));
			ad_displayUrl.setText(Act_AdList.adList.get(position).get("displayUrl"));
			
			ad_clicks_value.setText(Act_AdList.adList.get(position).get("clicks"));
			ad_cost_value.setText(Act_AdList.adList.get(position).get("cost"));
			ad_ctr_value.setText(Act_AdList.adList.get(position).get("ctr"));
			ad_avgcpc_value.setText(Act_AdList.adList.get(position).get("avgcpc"));
			
			
			String status = Act_AdList.adList.get(position).get("status");
			adStatus.setText(status);
			
			if(status.equals("ENABLED")){
				img_ad_status.setImageResource(R.drawable.enable);
			} else if(status.equals("PAUSED")){
				img_ad_status.setImageResource(R.drawable.pause);
			} else if(status.equals("DISABLED")){
				img_ad_status.setImageResource(R.drawable.delete);
			}
			
			
			return row;
		}
	};//textAdListAdapter

	
	
	/*
	 * Get ad list
	 */
	private void getAdList(){
		adList.clear();
		
		AdGroupAdResponseParser parser = new AdGroupAdResponseParser(
		Communication.postSOAP(AdGroupAdService.URL_ADGROUP_AD_SERVICE,
				AdGroupAdService.getAdList(adGroupId, DateProcessor.getDateRange(dateRangeItem)
						, statusItem)));
		
		responseErrorString = parser.checkForErrors();
		
		adList.addAll(parser.getAdList());	
	}
	
	
	
    /*
     * Async operation
     */
	private void runOperationAsync(final int operation, String message, boolean overlap) {

		//Stop if thread is alive
		if(thread.isAlive() && !overlap)
			return;
		
		//Show progress dialog
		final ProgressDialog progressDialog = ProgressDialog.show(this, "",
				message, true);

		//Check if Internet connection alive
		if(!isConnectionAvalable()){
			progressDialog.dismiss();
			return;
		}

		thread = new Thread(){
			public void run() {
				//Perform authentication
				new AuthService(Act_AdList.this, getApplication());
				
				//Perform operation
				if (AuthService.authToken != null) {
					try {
						switch (operation) {
						case OPERATION_GET_LIST:
							Act_AdList.this.getAdList();
							Act_AdList.this.getTip();
							break;
						case OPERATION_SET_STATUS:
							Act_AdList.this.setAdStatus();
							break;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				//Perform postoperation
				Act_AdList.this.runOnUiThread(new Runnable() {
					public void run() {
						
						progressDialog.dismiss();

						if (AuthService.authToken != null) {
							
							showOperationError(R.string.msg_title_error, responseErrorString);
							
							switch (operation) {
							case OPERATION_GET_LIST:
								textAdListAdapter.notifyDataSetChanged();
								showStatsTotal(SHOW_TOTALS_CLICKS_COST_CTR_AVGCPC);
								showTip();
								break;

							case OPERATION_SET_STATUS:
								runOperationAsync(OPERATION_GET_LIST,
										getString(R.string.progress_refreshing), true);
								break;
							}
			
						} else {
							Intent intent = new Intent(Act_AdList.this.getApplicationContext(),
									Act_Login.class);
							startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);
						}
					}
				});
			}
		};
		thread.start();
	
	}//runOperationAsync

	
	
	/*
     * Inflate Option menu called when menu button pressed (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_ad_list, menu);
        return true;
    }//onCreateOptionsMenu
    

    
    /*
     *Option menu selection handler  (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Intent intent;

    	switch (item.getItemId()) {
        
			case R.id.refresh_Ad: 
				runOperationAsync(OPERATION_GET_LIST, getString(R.string.progress_refreshing), false);
	            break;
    	
    		case R.id.add_Ad: 
        		intent = new Intent(this.getApplicationContext(), Act_AdOperation.class);
            	intent.putExtra("adGroupId", adGroupId);
    			intent.putExtra("campaignName", campaignName);
    			intent.putExtra("adGroupName", adGroupName);
            	startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);            	
                break;
            
            case R.id.switch_AccountAd: 
            	AuthService.performLogout(getApplication());
            	intent = new Intent(this.getApplicationContext(), Act_Login.class);
            	startActivityForResult(intent, REQUEST_REFRESH_REQUIRED);  
                break;
        }
        return true;
    }//onOptionsItemSelected
	
}
